package com.example.ams.service;

import com.example.ams.dto.OvertimeRecordDTO;
import com.example.ams.entity.Employee;
import com.example.ams.entity.OvertimeRecord;
import com.example.ams.repository.EmployeeRepository;
import com.example.ams.repository.OvertimeRecordRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 加班记录服务类
 * Overtime Record Service
 */
@Service
public class OvertimeRecordService {

    @Autowired
    private OvertimeRecordRepository overtimeRecordRepository;

    @Autowired
    private EmployeeRepository employeeRepository;

    private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 查询所有加班记录
     */
    public List<OvertimeRecordDTO> findAll() {
        return overtimeRecordRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 根据ID查询加班记录
     */
    public OvertimeRecordDTO findById(Long id) {
        OvertimeRecord record = overtimeRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("加班记录不存在，ID: " + id));
        return convertToDTO(record);
    }

    /**
     * 根据条件查询加班记录
     */
    public List<OvertimeRecordDTO> findByConditions(Long employeeId, String from, String to) {
        try {
            List<OvertimeRecord> records;

            if (employeeId != null && from != null && to != null) {
                Date startTime = parseDateTime(from + " 00:00:00");
                Date endTime = parseDateTime(to + " 23:59:59");
                records = overtimeRecordRepository.findByEmployeeIdAndTimeRange(employeeId, startTime, endTime);
            } else if (from != null && to != null) {
                Date startTime = parseDateTime(from + " 00:00:00");
                Date endTime = parseDateTime(to + " 23:59:59");
                records = overtimeRecordRepository.findByTimeRange(startTime, endTime);
            } else if (employeeId != null) {
                records = overtimeRecordRepository.findByEmployeeIdOrderByStartTimeDesc(employeeId);
            } else {
                records = overtimeRecordRepository.findAll();
            }

            return records.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误，请使用 yyyy-MM-dd 格式");
        }
    }

    /**
     * 创建加班记录
     */
    @Transactional
    public OvertimeRecordDTO create(OvertimeRecordDTO recordDTO) {
        // 验证员工是否存在
        Employee employee = employeeRepository.findById(recordDTO.getEmployeeId())
                .orElseThrow(() -> new RuntimeException("员工不存在，ID: " + recordDTO.getEmployeeId()));

        OvertimeRecord record = new OvertimeRecord();
        BeanUtils.copyProperties(recordDTO, record, "id", "createdAt", "employeeName", "empNo");

        OvertimeRecord saved = overtimeRecordRepository.save(record);
        return convertToDTO(saved);
    }

    /**
     * 删除加班记录
     */
    @Transactional
    public void delete(Long id) {
        if (!overtimeRecordRepository.existsById(id)) {
            throw new RuntimeException("加班记录不存在，ID: " + id);
        }
        overtimeRecordRepository.deleteById(id);
    }

    /**
     * Entity转DTO
     */
    private OvertimeRecordDTO convertToDTO(OvertimeRecord record) {
        OvertimeRecordDTO dto = new OvertimeRecordDTO();
        BeanUtils.copyProperties(record, dto);

        // 填充员工信息
        employeeRepository.findById(record.getEmployeeId()).ifPresent(employee -> {
            dto.setEmployeeName(employee.getName());
            dto.setEmpNo(employee.getEmpNo());
        });

        return dto;
    }

    /**
     * 解析日期时间
     */
    private Date parseDateTime(String dateTimeStr) throws ParseException {
        return DATETIME_FORMAT.parse(dateTimeStr);
    }
}

